package network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class ServerAPI {

	public static double[] getTagLocation(String tagId) {
		System.out.println(tagId);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse responseTags;
		int tagStatusCode = 0;
		String responseTagsString = "";
		double [] out  = new double[2];
		HttpPost httppost = new HttpPost("http://shopassistiot.apphb.com/Tags/GetLocation/"+tagId);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("id", tagId));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			responseTags = httpclient.execute(httppost);
			responseTagsString = EntityUtils.toString(responseTags.getEntity());
			tagStatusCode = responseTags.getStatusLine().getStatusCode();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.print(tagStatusCode);
		if (tagStatusCode == 200) {
			System.out.println(responseTagsString);
			try {
				JSONObject JSONObject = new JSONObject(responseTagsString);
				out[0] = Double.parseDouble(JSONObject.getString("Longitude"));
				out[1] = Double.parseDouble(JSONObject.getString("Latitude"));
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			

		}
		return out;
	}

}
